#!/usr/bin/env bash
set -euxo pipefail

# create mountpoints in /etc
mkdir -p "${BUILDROOT}"/etc/{cni,kubernetes}

# move issue files away from /etc
# to allow /run/issue and /run/issue.d to take precedence
mv "${BUILDROOT}/etc/issue.d" "${BUILDROOT}/usr/lib/issue.d" || true

# generate reproducible package manifest
mkdir -p "${BUILDROOT}/usr/share/constellation"
mkosi-chroot rpm -qa --qf '%{name};%{version};%{license}\n' --dbpath "/var/lib/rpm/" | LC_ALL=C sort | tee "${BUILDROOT}/usr/share/constellation/packagemanifest"
cp "${BUILDROOT}/usr/share/constellation/packagemanifest" "${OUTPUTDIR}/"

# copy rpmdb to outputs
cp "${BUILDROOT}"/var/lib/rpm/{rpmdb.sqlite-wal,rpmdb.sqlite-shm,rpmdb.sqlite} "${OUTPUTDIR}/"

# FIXME(msanft):
# Hack to satisfy Bazel's [output expectations](./BUILD.bazel).
# 2 Bazel packages can't share the same output paths, as it seems, and the
# files being copied around here aren't large, so copying them around doesn't
# hurt.
cp "${OUTPUTDIR}/packagemanifest" "${OUTPUTDIR}/lts-packagemanifest"
touch "${OUTPUTDIR}/lts-.rpm.lock"
cp "${OUTPUTDIR}/rpmdb.sqlite" "${OUTPUTDIR}/lts-rpmdb.sqlite"
cp "${OUTPUTDIR}/rpmdb.sqlite-shm" "${OUTPUTDIR}/lts-rpmdb.sqlite-shm"
cp "${OUTPUTDIR}/rpmdb.sqlite-wal" "${OUTPUTDIR}/lts-rpmdb.sqlite-wal"
cp "${OUTPUTDIR}/packagemanifest" "${OUTPUTDIR}/mainline-packagemanifest"
touch "${OUTPUTDIR}/mainline-.rpm.lock"
cp "${OUTPUTDIR}/rpmdb.sqlite" "${OUTPUTDIR}/mainline-rpmdb.sqlite"
cp "${OUTPUTDIR}/rpmdb.sqlite-shm" "${OUTPUTDIR}/mainline-rpmdb.sqlite-shm"
cp "${OUTPUTDIR}/rpmdb.sqlite-wal" "${OUTPUTDIR}/mainline-rpmdb.sqlite-wal"
